package com.chanceit.ssss.activity;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import net.tsz.afinal.FinalDb;
import net.tsz.afinal.http.AjaxCallBack;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.gl.GlobalVariable;
import org.gl.android.utils.GLApkVersionManger;
import org.gl.animation.ReverseInterpolator;
import org.gl.customview.Rotate3dAnimation;
import org.gl.customview.ScenesAnimationSteteI;
import org.gl.customview.ViewPath;
import org.gl.customview.gifview.GifView;
import org.gl.ui.manger.BaseActivity;
import org.gl.utils.AndroidUtil;
import org.gl.utils.AppConfig;
import org.gl.utils.Tip;
import org.gl.utils.WaitThreeSecond;
import org.gl.utils.lg;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.EditorInfo;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.chanceit.ssss.button.GoAddCarButtonOnClickImp;
import com.chanceit.ssss.button.GoSearchOnClickImp;
import com.chanceit.ssss.common.ActivityActionName;
import com.chanceit.ssss.common.IntentExtraDataKey;
import com.chanceit.ssss.common.ThridApp;
import com.chanceit.ssss.common.WebServicUrl;
import com.chanceit.ssss.data.DataSources;
import com.chanceit.ssss.data.UserInfo;
import com.chanceit.ssss.right.AddCarer;
import com.chanceit.ssss.right.AllCarer;
import com.chanceit.ssss.right.Bussices;
import com.chanceit.ssss.right.InShop;
import com.chanceit.ssss.right.Order;
import com.chanceit.ssss.right.Report;
import com.chanceit.ssss.right.ReveiceCar;
import com.chanceit.ssss.right.RightGroup;
import com.chanceit.ssss.right.Safe;
import com.chanceit.ssss.right.ToDoCom;
import com.chanceit.ssss.right.TodoOrder;
import com.google.analytics.tracking.android.EasyTracker;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
public class LoginActivity extends BaseActivity implements OnClickListener {

	/**
	 * The default email to populate the email field with.
	 */
	public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL";

	public static final int NoNetWork = 600;
	public static final int OutMaxRetryCount = 700;
	public static final int IOException = 800;
	public static final int JSONException = 900;

	/**
	 * Keep track of the login task to ensure we can cancel it if requested.
	 */
	private UserLoginTask mAuthTask = null;

	// Values for email and password at the time of the login attempt.
	private String mEmail;
	private String mPassword;

	// UI references.
	private EditText mEmailView;
	private EditText mPasswordView;
	private View mLoginFormView;
	private View mLoginStatusView;
	private TextView mLoginStatusMessageView;
	private CheckBox chechBox_rember;

	/**
	 * 登陆过程中动画最少持续的时间
	 */
	int login_time_total = 2000;

	/**
	 * 后台服务
	 */
	Intent intent_for_service = new Intent(
			"com.chanceit.ssss.service.myservice");

	@Override
	protected void onResume() {
		super.onResume();
		((Button) findViewById(R.id.iv_setting))
				.setText(getString(R.string.title_activity_go_setting)
						+ AndroidUtil.getServerIPConfig() + ":"
						+ AndroidUtil.getServerPortConfig());
		delayMillis = 3000;
		AndroidUtil.checkNetInActivity(this);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		if (GlobalVariable.isFirstUseApp()) {
			onClick(findViewById(R.id.iv_setting));
		}
		chechBox_rember = (CheckBox) findViewById(R.id.checkBox_rember);
		// Set up the login form.
		mEmail = getIntent().getStringExtra(EXTRA_EMAIL);
		String[] mAccountInfo = AndroidUtil.getAccountPassword();
		if (mEmail == null) {
			mEmail = mAccountInfo[0];
			mPassword = mAccountInfo[1];
			if (!TextUtils.isEmpty(mEmail)) {
				chechBox_rember.setChecked(true);
			}
		}
		mEmailView = (EditText) findViewById(R.id.email);
		if (!TextUtils.isEmpty(mEmail)) {
			mEmailView.setText(mEmail);
			mEmailView.setSelection(mEmail.length());
		}

		mPasswordView = (EditText) findViewById(R.id.password);
		mPasswordView.setText(mPassword);
		if (!TextUtils.isEmpty(mPassword)) {
			mPasswordView.setText(mPassword);
			mPasswordView.setSelection(mPassword.length());
		}
		mPasswordView
				.setOnEditorActionListener(new TextView.OnEditorActionListener() {
					@Override
					public boolean onEditorAction(TextView textView, int id,
							KeyEvent keyEvent) {
						if (id == R.id.login || id == EditorInfo.IME_NULL) {
							attemptLogin();
							return true;
						}
						return false;
					}
				});

		mLoginFormView = findViewById(R.id.login_form);
		mLoginStatusView = findViewById(R.id.login_status);
		mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);

		findViewById(R.id.sign_in_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						attemptLogin();
					}
				});
		chechBox_rember
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton arg0,
							boolean arg1) {
						if (arg1) {

						}
					}
				});

		initView();
		initAnima();
		mediaPlayer = MediaPlayer.create(getBaseContext(), R.raw.burst);
		// try {
		// mediaPlayer.prepare();
		// } catch (IllegalStateException e) {
		// e.printStackTrace();
		// mediaPlayer=null;
		// } catch (IOException e) {
		// e.printStackTrace();
		// mediaPlayer= null;
		// }
		startService(intent_for_service);
		GLApkVersionManger gl = new GLApkVersionManger();
		gl.autoManger(this, "4Sshop");

		initData();
		initAccountSpinnerView();
	}

	private ScenesAnimationSteteI staue;
	private ScenesAnimationSteteI staue_Login_onStart;
	private ScenesAnimationSteteI staue_Login_onDone;
	private ScenesAnimationSteteI staue_Login_onFail;

	private void initAnima() {
		staue_Login_onStart = new Login_onStart();
		staue_Login_onDone = new Login_onDone();
		staue_Login_onFail = new Login_onFail();

	}

	View ly_login;
	GifView car;
	View cloud1;
	View cloud2;
	View cloud3;
	View mounttion;
	View shop;
	View ll_shopinfo;
	TextView order;
	TextView all;
	TextView inshop;
	View add;
	View orderReceive;
	View ind_bottom_top;

	/**
	 * for sale
	 */
	View carefor, business, todo_order, todo_com;

	private View report;
	/**
	 * 安全监测
	 */
	private View safe;

	private void initView() {
		ly_login = findViewById(R.id.textView2);
		car = (GifView) findViewById(R.id.progressBar1);
		cloud1 = findViewById(R.id.textView3);
		cloud2 = findViewById(R.id.textView4);
		cloud3 = findViewById(R.id.textView5);
		mounttion = findViewById(R.id.textView1);
		ll_shopinfo = findViewById(R.id.ll_shopinfo);
		all = (TextView) findViewById(R.id.all);
		inshop = (TextView) findViewById(R.id.inshop);
		order = (TextView) findViewById(R.id.order);
		add = findViewById(R.id.add);
		orderReceive = findViewById(R.id.orderReceive);
		shop = findViewById(R.id.shop);
		ind_bottom_top = findViewById(R.id.ind_bottom_top);
		ly_login.setOnClickListener(this);
		all.setOnClickListener(this);
		orderReceive.setOnClickListener(new GoSearchOnClickImp(this));
		inshop.setOnClickListener(this);
		order.setOnClickListener(this);
		// add.setOnClickListener(this);
		add.setOnClickListener(new GoAddCarButtonOnClickImp(this));
		car.setGifImage(R.drawable.car);

		// for sale
		carefor = findViewById(R.id.carefor);
		carefor.setOnClickListener(this);
		business = findViewById(R.id.business);
		business.setOnClickListener(this);
		todo_order = findViewById(R.id.todo_order);
		todo_com = findViewById(R.id.todo_complaint);
		report = findViewById(R.id.report);
		safe = findViewById(R.id.safe);

		setViewTouchMode();
		setViewRight();
	}

	private void setViewRight() {
		all.setTag(new AllCarer());
		order.setTag(new Order());
		inshop.setTag(new InShop());
		add.setTag(new AddCarer());
		orderReceive.setTag(new ReveiceCar());
		business.setTag(new Bussices());
		carefor.setTag(new Bussices());
		todo_com.setTag(new ToDoCom());
		todo_order.setTag(new TodoOrder());
		report.setTag(new Report());
		safe.setTag(new Safe());
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@Override
	protected void onStart() {
		super.onStart();
		Animation mAnimation = AnimationUtils.loadAnimation(getBaseContext(),
				R.anim.slide_right);
		mAnimation.setDuration(1000);
		if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			mAnimation.setInterpolator(getBaseContext(),
					android.R.interpolator.overshoot);
		} else {
			LinearInterpolator v = new LinearInterpolator();
			mAnimation.setInterpolator(v);
		}
		car.startAnimation(mAnimation);
		EasyTracker.getInstance().activityStart(this); // Add this method.
	}

	@Override
	protected void onStop() {
		super.onStop();
		EasyTracker.getInstance().activityStop(this);

	}

	private void startScreenAnimation() {
		if (!preIsFaile && staue != null) {
			staue.startAnimation();
		}

	}

	@Override
	protected void onPause() {
		super.onPause();
		delayMillis = 8000;
	}

	@Override
	protected void onDestroy() {
		car.destroy();
		if (mediaPlayer != null) {
			mediaPlayer.release();
			mediaPlayer = null;
		}
		stopService(intent_for_service);
		super.onDestroy();
	};

	ViewPath ViewPath_c1;
	ViewPath ViewPath_c2;
	ViewPath ViewPath_c3;
	ViewPath car_p;
	Handler handler = new Handler();
	Animation sild_left_out;

	class Login_onStart implements ScenesAnimationSteteI {
		int lastMountionX = -1000;
		final int initLength = mounttion.getScrollX();
		int currentlength = 0;

		public Login_onStart() {
			sild_left_out = new TranslateAnimation(Animation.RELATIVE_TO_SELF,
					0f, Animation.RELATIVE_TO_SELF, -1.5f,
					Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF,
					0f);
			sild_left_out.setDuration(1500);
			// sild_left_out.setFillAfter(true);

		}

		@Override
		public void startAnimation() {
			// showProgress(false);
			findViewById(R.id.title).setVisibility(View.GONE);
			findViewById(R.id.bottom).setVisibility(View.GONE);
			sild_left_out.setAnimationListener(new AnimationListener() {
				@Override
				public void onAnimationStart(Animation animation) {
					ly_login.setVisibility(View.VISIBLE);
				}

				@Override
				public void onAnimationRepeat(Animation animation) {
				}

				@Override
				public void onAnimationEnd(Animation animation) {
					ly_login.setVisibility(View.INVISIBLE);
				}
			});
			ly_login.startAnimation(sild_left_out);

			ViewPath_c1 = new ViewPath(cloud1);
			ViewPath_c2 = new ViewPath(cloud2);
			ViewPath_c3 = new ViewPath(cloud3);

			handler.removeCallbacks(mRunnable);
			handler.post(mRunnable);

		}

		/**
		 * 动画服务的Runnable
		 */
		Runnable mRunnable = new Runnable() {

			@Override
			public void run() {
				mounttion.scrollTo(-currentlength, 0);
				if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
					cloud1.layout(ViewPath_c1.l + currentlength / 100,
							ViewPath_c1.t, ViewPath_c1.r + currentlength / 100,
							ViewPath_c1.b);
					cloud2.layout(ViewPath_c2.l + currentlength / 100,
							ViewPath_c2.t, ViewPath_c2.r + currentlength / 100,
							ViewPath_c2.b);
					cloud3.layout(ViewPath_c3.l + currentlength / 100,
							ViewPath_c3.t, ViewPath_c3.r + currentlength / 100,
							ViewPath_c3.b);
				} else {
					// cloud1.layout(ViewPath_c1.l + currentlength,
					// ViewPath_c1.t,
					// ViewPath_c1.r + currentlength, ViewPath_c1.b);
					// cloud2.layout(ViewPath_c2.l + currentlength,
					// ViewPath_c2.t,
					// ViewPath_c2.r + currentlength, ViewPath_c2.b);
					// cloud3.layout(ViewPath_c3.l + currentlength,
					// ViewPath_c3.t,
					// ViewPath_c3.r + currentlength, ViewPath_c3.b);
				}

				if (currentlength > lastMountionX) {
					currentlength = currentlength - AnimationSpeed / FPS;
					handler.postDelayed(this, 1000 / FPS);
				} else {
					currentMontionScrollLength = currentlength;
					currentlength = initLength;
				}
			}
		};

	}

	int currentMontionScrollLength;

	class Login_onDoing implements ScenesAnimationSteteI {

		@Override
		public void startAnimation() {

		}

	}

	class Login_onDone implements ScenesAnimationSteteI {
		private ScaleAnimation scale_indr;
		int carLl = 0;
		int carLl_inshop = 100;
		private Animation sild_right_shop;
		private AnimationSet fade_right_in;
		private AnimationSet fade_left_in;
		private AnimationSet fade_top_in;
		private AnimationSet fade_bottom_in;

		Login_onDone() {
			sild_right_shop = new TranslateAnimation(
					Animation.RELATIVE_TO_SELF, 1.5f,
					Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF,
					0f, Animation.RELATIVE_TO_SELF, 0f);
			sild_right_shop.setDuration(1000);
			sild_right_shop.setFillAfter(true);
			sild_right_shop.setAnimationListener(new AnimationListener() {
				@Override
				public void onAnimationStart(Animation animation) {
					shop.setVisibility(View.VISIBLE);

				}

				@Override
				public void onAnimationRepeat(Animation animation) {
				}

				@Override
				public void onAnimationEnd(Animation animation) {
					car.showCover();
				}
			});
			scale_indr = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1f,
					Animation.RELATIVE_TO_SELF, 2.0f,
					Animation.RELATIVE_TO_PARENT, 1.0f);
			// scale_indr.setRepeatCount(1);
			// scale_indr.setRepeatMode(Animation.REVERSE);
			{
				// scale_indr.setInterpolator(context,
				// android.R.interpolator.overshoot);
			}
			scale_indr.setDuration(1000);
			scale_indr.setFillAfter(true);
			fade_right_in = (AnimationSet) AnimationUtils.loadAnimation(
					getBaseContext(), R.anim.dangling_scale_right_in);
			fade_top_in = (AnimationSet) AnimationUtils.loadAnimation(
					getBaseContext(), R.anim.dangling_scale_top_in);
			fade_left_in = (AnimationSet) AnimationUtils.loadAnimation(
					getBaseContext(), R.anim.dangling_scale_left_in);
			fade_bottom_in = (AnimationSet) AnimationUtils.loadAnimation(
					getBaseContext(), R.anim.dangling_scale_bottom_in);
			fade_left_in.setAnimationListener(new AnimationListener() {

				@Override
				public void onAnimationStart(Animation animation) {
				}

				@Override
				public void onAnimationRepeat(Animation animation) {
				}

				@Override
				public void onAnimationEnd(Animation animation) {
					Animation temp = new TranslateAnimation(
							Animation.RELATIVE_TO_PARENT, -0.03f,
							Animation.RELATIVE_TO_PARENT, 0f,
							Animation.RELATIVE_TO_PARENT, 0f,
							Animation.RELATIVE_TO_PARENT, 0f);
					temp.setDuration(800);
					inshop.startAnimation(temp);
				}
			});
			fade_right_in.setAnimationListener(new AnimationListener() {

				@Override
				public void onAnimationStart(Animation animation) {
				}

				@Override
				public void onAnimationRepeat(Animation animation) {
				}

				@Override
				public void onAnimationEnd(Animation animation) {
					Animation temp = new TranslateAnimation(
							Animation.RELATIVE_TO_PARENT, 0.03f,
							Animation.RELATIVE_TO_PARENT, 0f,
							Animation.RELATIVE_TO_PARENT, 0f,
							Animation.RELATIVE_TO_PARENT, 0f);
					temp.setDuration(800);
					all.startAnimation(temp);
				}
			});

		}

		@Override
		public void startAnimation() {

			car_p = new ViewPath(car);
			shop.startAnimation(sild_right_shop);

			order.startAnimation(fade_top_in);
			add.startAnimation(fade_bottom_in);
			inshop.startAnimation(fade_left_in);
			all.startAnimation(fade_right_in);
			orderReceive.startAnimation(fade_bottom_in);

			ind_bottom_top.startAnimation(scale_indr);
			ind_bottom_top.setVisibility(View.VISIBLE);

			handler.removeCallbacksAndMessages(null);
			handler.post(new Runnable() {
				@Override
				public void run() {
					if (carLl < carLl_inshop) {
						carLl += carLl_inshop / FPS;
						// car.layout(car_p.l + carLl, car_p.t, car_p.r + carLl,
						// car_p.b);
						handler.postDelayed(this, FPS);
						mounttion.scrollTo(currentMontionScrollLength + carLl,
								0);
					} else {

					}

				}
			});
		}

	}

	/**
	 * 上次一次登录请求是否失败,下次不执行动画.
	 */
	boolean preIsFaile = false;

	class Login_onFail implements org.gl.customview.ScenesAnimationSteteI {

		@Override
		public void startAnimation() {
			showProgress(false);
			if (preIsFaile != true) {
				Animation mAnimatio = sild_left_out;
				mAnimatio.setInterpolator(new ReverseInterpolator());
				sild_left_out.setAnimationListener(new AnimationListener() {
					@Override
					public void onAnimationStart(Animation animation) {
						ly_login.setVisibility(View.VISIBLE);
						preIsFaile = true;
					}

					@Override
					public void onAnimationRepeat(Animation animation) {
					}

					@Override
					public void onAnimationEnd(Animation animation) {
						// ly_login.setVisibility(View.INVISIBLE);
					}
				});
				ly_login.startAnimation(mAnimatio);
			}
		}

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			// that hierarchy.
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}

	/**
	 * Attempts to sign in or register the account specified by the login form.
	 * If there are form errors (invalid email, missing fields, etc.), the
	 * errors are presented and no actual login attempt is made.
	 */
	public void attemptLogin() {
		if (mAuthTask != null) {
			return;
		}

		// Reset errors.
		mEmailView.setError(null);
		mPasswordView.setError(null);

		// Store values at the time of the login attempt.
		mEmail = mEmailView.getText().toString();
		mPassword = mPasswordView.getText().toString();

		boolean cancel = false;
		View focusView = null;

		// Check for a valid password.
		if (TextUtils.isEmpty(mPassword)) {
			mPasswordView.setError(getString(R.string.error_field_required));
			focusView = mPasswordView;
			cancel = true;
		} else if (mPassword.length() < 4) {
			mPasswordView.setError(getString(R.string.error_invalid_password));
			focusView = mPasswordView;
			cancel = true;
		}

		// Check for a valid email address.
		if (TextUtils.isEmpty(mEmail)) {
			mEmailView.setError(getString(R.string.error_field_required));
			focusView = mEmailView;
			cancel = true;
		}
		// else if (!mEmail.contains("@")) {
		// mEmailView.setError(getString(R.string.error_invalid_email));
		// focusView = mEmailView;
		// cancel = true;
		// }

		if (cancel) {
			// There was an error; don't attempt login and focus the first
			// form field with an error.
			focusView.requestFocus();
		} else {
			// Show a progress spinner, and kick off a background task to
			// perform the user login attempt.
			mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
			showProgress(true);
			mAuthTask = new UserLoginTask();
			mAuthTask.execute((Void) null);
		}
	}

	/**
	 * Shows the progress UI and hides the login form.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	private void showProgress(final boolean show) {
		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
		// for very easy animations. If available, use these APIs to fade-in
		// the progress spinner.
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			int shortAnimTime = getResources().getInteger(
					android.R.integer.config_shortAnimTime);

			mLoginStatusView.setVisibility(View.VISIBLE);
			mLoginStatusView.animate().setDuration(shortAnimTime)
					.alpha(show ? 1 : 0);
			// .setListener(new AnimatorListenerAdapter() {
			// @Override
			// public void onAnimationEnd(Animator animation) {
			//
			// }
			// });
			mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
			// mLoginFormView.setVisibility(View.VISIBLE);
			// mLoginFormView.animate().setDuration(shortAnimTime)
			// .alpha(show ? 0 : 1)
			// .setListener(new AnimatorListenerAdapter() {
			// @Override
			// public void onAnimationEnd(Animator animation) {
			// mLoginFormView.setVisibility(show ? View.GONE
			// : View.VISIBLE);
			// }
			// });
		} else {
			// The ViewPropertyAnimator APIs are not available, so simply show
			// and hide the relevant UI components.
			mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
			// mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
		}
	}

	/**
	 * Represents an asynchronous login/registration task used to authenticate
	 * the user.
	 */
	public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
		int isfinish = 0;
		String msg = "";

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			staue = staue_Login_onStart;
			startScreenAnimation();
			hideSoftInput(mEmailView);
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			HttpPost post = new HttpPost(WebServicUrl.login);
			List<BasicNameValuePair> par = new ArrayList<BasicNameValuePair>();
			par.add(new BasicNameValuePair("account", mEmail));
			par.add(new BasicNameValuePair("password", mPassword));
			par.add(new BasicNameValuePair("mobile", "mobile"));
			long current = System.currentTimeMillis();
			boolean isRetry = true;
			final int maxRetryCount = 5;
			int currentRetryCount = 0;
			while (isRetry) {
				if (!AndroidUtil.checkNetwork()) {
					isRetry = false;
					isfinish = NoNetWork;
					return false;
				}
				if (currentRetryCount >= maxRetryCount) {
					isRetry = false;
					isfinish = OutMaxRetryCount;
					return false;
				}
				currentRetryCount++;
				if (currentRetryCount == 2) {
					handler.post(new Runnable() {

						@Override
						public void run() {
							Tip.show("网络不好,程序正在尝试多次连接");
						}
					});
				}
				lg.i(TAG, "login retry count>>" + currentRetryCount);
				try {
					post.setEntity(new UrlEncodedFormEntity(par, HTTP.UTF_8));
					HttpResponse mHttpResponse = GlobalVariable.DefaultHttpClient
							.execute(post);
					isfinish = mHttpResponse.getStatusLine().getStatusCode();
					if (isfinish == 200) {
						InputStream is = mHttpResponse.getEntity().getContent();
						byte bytes[] = new byte[1024 * 4];
						StringBuilder sb = new StringBuilder();
						int x;
						while ((x = is.read(bytes)) != -1) {
							sb.append(new String(bytes, 0, x));
						}
						lg.i(TAG, sb.toString());
						JSONObject json_result = new JSONObject(sb.toString());
						isfinish = json_result.optInt("code");
						if (isfinish == 0) {
							isfinish = 200;
							GlobalVariable.getGlobalInstance().intent.putExtra(
									IntentExtraDataKey.ACCOUNE_ID,
									json_result.optInt("accountId"));
							GlobalVariable.UserInfo = json_result;
							JSONObject commpany = json_result
									.optJSONObject("company");
							GlobalVariable.getGlobalInstance().intent
									.putExtra(
											IntentExtraDataKey.COMPANYID,
											commpany.optString(IntentExtraDataKey.COMPANYID));
							if (preIsFaile) {// if previous is login fail
								handler.post(new Runnable() {

									@Override
									public void run() {
										ly_login.setVisibility(View.INVISIBLE);
									}
								});
								preIsFaile = false;
							}
							isRetry = false;
						} else {
							isfinish = 2;
							isRetry = false;
						}
					} else {
						isfinish = 500;
					}
				} catch (UnsupportedEncodingException e1) {
					e1.printStackTrace();
					isfinish = 500;
				} catch (ClientProtocolException e) {
					e.printStackTrace();
					isfinish = 500;
				} catch (IOException e) {
					e.printStackTrace();
					isfinish = IOException;
				} catch (JSONException e) {
					e.printStackTrace();
					isfinish = JSONException;
				} finally {
					if (!preIsFaile
							&& System.currentTimeMillis() - current < login_time_total) {//
						try {
							Thread.sleep(login_time_total
									- (System.currentTimeMillis() - current));

						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}

			return (isfinish == 200) ? true : false;
		}

		@Override
		protected void onPostExecute(Boolean success) {
			mAuthTask = null;
			showProgress(false);
			if (success) {
				UserInfo ui = new UserInfo();
				ui.setUserName(mEmail);
				ui.setPassWord(mPassword);
				if (chechBox_rember.isChecked()) {
					ui.setIsRember("1");
					AndroidUtil.saveAccountPassword(mEmail, mPassword);

				}
				finalDb.deleteByWhere(UserInfo.class,
						"username = '" + ui.getUserName() + "'");

				finalDb.save(ui);

				staue = staue_Login_onDone;
				handlerUserInfo();

			} else {

				switch (isfinish) {
				case 2:
					msg = getString(R.string.error_incorrect_password);
					break;
				case NoNetWork:
					msg = "没有可使用的网络";
					break;
				case OutMaxRetryCount:
					msg = "尝试多次连接失败";
					break;
				case IOException:
					msg = "网络不够流畅";
					break;
				case JSONException:
					msg = "服务器返回数据格式异常";
					break;
				default:
					msg = getString(R.string.err_server);
					break;
				}
				mPasswordView.setError(msg);
				chechBox_rember.setChecked(false);
				mPasswordView.requestFocus();
				staue = staue_Login_onFail;
				startScreenAnimation();
				showSoftInput(mPasswordView);
			}
		}

		@Override
		protected void onCancelled() {
			mAuthTask = null;

		}
	}

	long delayMillis = 8000;

	protected MediaPlayer mediaPlayer;

	@Override
	public void onClick(View v) {
		Intent intent = GlobalVariable.getGlobalInstance().intent;
		switch (v.getId()) {
		case R.id.iv_passowrd_update:
			startActivity(GlobalVariable.getGlobalInstance().intent
					.setAction(ActivityActionName.PASSWORD));
			// finish();
			break;
		case R.id.iv_setting:
			startActivity(GlobalVariable.getGlobalInstance().intent
					.setAction(ActivityActionName.SETTING));
			break;
		case R.id.all:
			// intent.setAction(ActivityActionName.HOME);
			// intent.putExtra(IntentExtraDataKey.HOME_SELECT_PAGE,
			// IntentExtraDataKey.HOME_SELECT_PAGE_ALL);
			// startActivity(intent);
			startActivityForResult(
					GlobalVariable.getGlobalInstance().intent
							.setAction(ActivityActionName.SEARCH),
					IntentExtraDataKey.FOR_RESULT_SEARCHID);
			break;
		case R.id.order:
			intent.setAction(ActivityActionName.HOME);
			intent.putExtra(IntentExtraDataKey.HOME_SELECT_PAGE,
					IntentExtraDataKey.HOME_SELECT_PAGE_ORDER);
			startActivity(intent);
			break;
		case R.id.inshop:
			intent.setAction(ActivityActionName.HOME);
			intent.putExtra(IntentExtraDataKey.HOME_SELECT_PAGE,
					IntentExtraDataKey.HOME_SELECT_PAGE_INSHOP);
			startActivity(intent);
			break;
		case R.id.add:
			intent.setAction(ActivityActionName.CARER);
			startActivity(intent);
			break;
		case R.id.carefor:
			intent.setAction(ActivityActionName.CareCar);
			intent.putExtra(IntentExtraDataKey.BUSINESS_TYPE,
					DataSources.BusinessType_birthday);
			startActivity(intent);
			break;
		case R.id.business:
			intent.setAction(ActivityActionName.Business);
			startActivity(intent);
			break;
		case R.id.todo_order:
			intent.putExtra(IntentExtraDataKey.TODO_TYPE,
					IntentExtraDataKey.TODO_TYPE_ORDER);
			intent.setAction(ActivityActionName.TodoList);
			startActivity(intent);
			break;
		case R.id.todo_complaint:
			intent.putExtra(IntentExtraDataKey.TODO_TYPE,
					IntentExtraDataKey.TODO_TYPE_COM);
			intent.setAction(ActivityActionName.TodoList);
			startActivity(intent);
			break;
		case R.id.report:
			intent.setAction(ActivityActionName.ReportActivity);
			startActivity(intent);
			break;
		case R.id.safe:
			intent.setAction(ActivityActionName.SafeActivity);
			startActivity(intent);
			break;
		case R.id.bt_opencard:
			new ThridApp().openThridApp(this,
					ActivityActionName.OpenCardMainActivity,
					"cn.chanceit.card", "CardActivity.apk");
			break;
		default:
			break;
		}

	}

	public void handlerUserInfo() {
		JSONObject user = GlobalVariable.UserInfo;
		if (user == null) {
			Tip.show("UserInfo is null");
			return;
		}
		handlerFunViewByRight(user.optJSONObject("role").optJSONArray("rights"));
	}

	/**
	 * 根据ROLE 确定界面的功能模块隐藏和显示
	 * 
	 * @param role
	 */
	private void handlerFunViewByRight(JSONArray jsonRight) {

		ll_shopinfo.setVisibility(View.VISIBLE);
		setViewVisRight(orderReceive, jsonRight);
		if (orderReceive.getVisibility() == View.GONE) {

			LinearLayout ll_add_orderReceiver = (LinearLayout) findViewById(R.id.ll_add_orderReceiver);
			ll_add_orderReceiver.setWeightSum(1);
			LinearLayout.LayoutParams m = (LayoutParams) add.getLayoutParams();
			m.leftMargin = 0;
			add.setLayoutParams(m);
			add.invalidate();
		} else {
			startScreenAnimation();
		}
		setViewVisRight(all, jsonRight);
		setViewVisRight(order, jsonRight);
		setViewVisRight(inshop, jsonRight);
		setViewVisRight(add, jsonRight);

		setViewVisRight(business, jsonRight);
		setViewVisRight(carefor, jsonRight);
		setViewVisRight(todo_com, jsonRight);
		setViewVisRight(todo_order, jsonRight);
		setViewVisRight(report, jsonRight);
		setViewVisRight(safe, jsonRight);
		if (inshop.getVisibility() == View.GONE) {
			LinearLayout.LayoutParams m = (LayoutParams) all.getLayoutParams();
			m.leftMargin = 0;
			all.setLayoutParams(m);
			all.invalidate();
		} else {
			handler.post(run_todo_num);
		}
		car.showCover();

	}

	private void setViewVisRight(View view, JSONArray jsonRight) {
		if (view.getTag() instanceof RightGroup) {
			view.setVisibility(((RightGroup) view.getTag())
					.isHasRight(jsonRight) ? View.VISIBLE : View.GONE);
		}

	}

	void getToDoNum() {
		DataSources ds = new DataSources();
		ds.getReminder(null, 0, new AjaxCallBack<String>() {

			@Override
			public void onSuccess(String t) {
				super.onSuccess(t);
				JSONObject ja;
				try {
					ja = new JSONObject(t);
					// FIXME
					if (!order.getText().equals("" + ja.optInt("reserve"))) {
						if (ja.optInt("reserve") > 0) {
							order.setText("" + ja.optInt("reserve"));
							final float centerX = order.getWidth() / 2.0f;
							final float centerY = order.getHeight() / 2.0f;
							Rotate3dAnimation rotation = new Rotate3dAnimation(
									0, 360, centerX, centerY, 360.0f, false);
							rotation.setDuration(1200);
							rotation.setFillAfter(true);
							rotation.setInterpolator(new DecelerateInterpolator());
							order.startAnimation(rotation);
							if (mediaPlayer != null) {
								try {
									mediaPlayer.start();
								} catch (IllegalStateException e) {
									e.printStackTrace();
									mediaPlayer = null;
								}
							}
							showNotification("有新的预约");
						} else {
							order.setText("0");
						}
					}

					if (!inshop.getText().equals("" + ja.optInt("inshopuser"))) {
						if (ja.optInt("inshopuser") > 0) {
							inshop.setText("" + ja.optInt("inshopuser"));
							final float centerX2 = inshop.getWidth() / 2.0f;
							final float centerY2 = inshop.getHeight() / 2.0f;
							Rotate3dAnimation rotation2 = new Rotate3dAnimation(
									0, 360, centerX2, centerY2, 240.0f, false);
							rotation2.setDuration(1000);
							rotation2.setFillAfter(true);
							rotation2
									.setInterpolator(new DecelerateInterpolator());
							rotation2.setStartOffset(2000);
							inshop.startAnimation(rotation2);
							if (mediaPlayer != null) {
								handler.postDelayed(new Runnable() {

									@Override
									public void run() {
										try {
											mediaPlayer.start();
										} catch (IllegalStateException e) {
											e.printStackTrace();
											mediaPlayer = null;
										}
									}
								}, 2000);

							}
							showNotification("有用户到店");
						} else {
							inshop.setText("0");
						}
					}
					// all.setText(ja.optInt("complaint"));
				} catch (JSONException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	Runnable run_todo_num = new Runnable() {
		@Override
		public void run() {
			getToDoNum();
			handler.postDelayed(this, delayMillis);
		}
	};

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case IntentExtraDataKey.FOR_RESULT_SEARCHID:
			if (resultCode == RESULT_OK) {
				if (data != null) {
					GlobalVariable.getGlobalInstance().intent
							.putExtra(IntentExtraDataKey.ACCOUNE_ID, data
									.getIntExtra(IntentExtraDataKey.ACCOUNE_ID,
											-1));
					GlobalVariable.getGlobalInstance().intent
							.setAction(ActivityActionName.ORDER_RECEIVE);
					startActivity(GlobalVariable.getGlobalInstance().intent);
				}
			}
			break;

		default:
			break;
		}
	};

	@Override
	public void onBackPressed() {
		if (staue == staue_Login_onDone) {
			if (!WaitThreeSecond.start()) {
				Tip.show(getString(R.string.exit_again_pressed));
				return;
			}
		}
		super.onBackPressed();
	}

	/**
	 * 处理焦点问题引起的不能点击
	 */
	private void setViewTouchMode() {

		all.setFocusable(false);
		all.setFocusableInTouchMode(false);
		order.setFocusable(false);
		order.setFocusableInTouchMode(false);
		inshop.setFocusable(false);
		inshop.setFocusableInTouchMode(false);
		add.setFocusable(false);
		add.setFocusableInTouchMode(false);
		orderReceive.setFocusable(false);
		orderReceive.setFocusableInTouchMode(false);
		business.setFocusable(false);
		business.setFocusableInTouchMode(false);
		carefor.setFocusable(false);
		carefor.setFocusableInTouchMode(false);
		todo_com.setFocusable(false);
		todo_com.setFocusableInTouchMode(false);
		todo_order.setFocusable(false);
		todo_order.setFocusableInTouchMode(false);
		report.setFocusable(false);
		report.setFocusableInTouchMode(false);
		safe.setFocusable(false);
		safe.setFocusableInTouchMode(false);
	}

	private EditText et_name;
	private View ib_spinner;
	protected View listView;
	private PopupWindow pop;
	private ArrayList<UserInfo> qqName;
	private MyAdapter adapter;

	private FinalDb finalDb;

	private void initData() {

		// TODO
		finalDb = FinalDb.create(this, AppConfig.DB_NAME, false);
		List<UserInfo> users = finalDb.findAll(UserInfo.class);
		// List<UserInfo> users = finalDb.findAll(UserInfo.class, "id");
		if (users != null && users.size() > 0) {
			qqName = (ArrayList<UserInfo>) users;
		}

	}

	private void initAccountSpinnerView() {
		et_name = mEmailView;
		ib_spinner = findViewById(R.id.ib_spinner);
		if (qqName == null || qqName.size() <= 0) {
			ib_spinner.setVisibility(View.GONE);
		}
		ib_spinner.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				// 弹出下拉列表
				ListView listView = new ListView(getApplicationContext());
				listView.setCacheColorHint(0x00000000);// 滑动时 不变色
				listView.setVerticalScrollBarEnabled(false);
				listView.setBackgroundResource(R.drawable.bg_edit);
				adapter = new MyAdapter();
				listView.setAdapter(adapter);

				pop = new PopupWindow(listView, et_name.getWidth(),
						LayoutParams.WRAP_CONTENT, true);

				// pop隐藏
				pop.setBackgroundDrawable(new ColorDrawable(0x00000000));

				pop.showAsDropDown(et_name, 0, AndroidUtil.dipToPx(12));
			}
		});
	}

	class MyAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return qqName.size();
		}

		@Override
		public Object getItem(int position) {
			return qqName.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			// 第一种：
			// View view = View.inflate(getApplicationContext(), R.layout.item,
			// null);
			// 第二种：
			LayoutInflater inflater = LayoutInflater
					.from(getApplicationContext());
			View view = inflater.inflate(R.layout.spinner_item_check_text,
					parent, false);
			view.setBackgroundResource(R.drawable.bg_bule_button);
			TextView tv_name = (TextView) view.findViewById(android.R.id.text1);
			// ImageButton delete = (ImageButton)
			// view.findViewById(R.id.delete);
			tv_name.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
			tv_name.setText(qqName.get(position).getUserName());
			tv_name.setTextColor(0xffffffff);
			tv_name.setGravity(Gravity.LEFT);
			tv_name.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					et_name.setText(qqName.get(position).getUserName());
					if (!TextUtils.isEmpty(qqName.get(position).getIsRember())
							&& qqName.get(position).getIsRember().equals("1")) {
						mPasswordView.setText(qqName.get(position)
								.getPassWord());
						chechBox_rember.setChecked(true);
					} else {
						mPasswordView.setText("");
						chechBox_rember.setChecked(false);
					}
					pop.dismiss();
				}
			});

			// delete.setOnClickListener(new OnClickListener() {
			//
			// @Override
			// public void onClick(View v) {
			//
			// qqName.remove(position);
			//
			// adapter.notifyDataSetChanged();
			// }
			// });

			return view;
		}

	}

	void showNotification(String message) {
		if (delayMillis > 3000) {
			return;
		}
		Intent startIntent = new Intent();
		;
		try {
			startIntent.setClass(this,
					Class.forName("com.chanceit.ssss.activity.LoginActivity"));
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		// 这里是为了判断是否是点击notification后到的详细界面

		startIntent.putExtra("onlineFlag", true);

		startIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
				| Intent.FLAG_ACTIVITY_CLEAR_TOP);

		showNotification(this, "通知:", message, 0, startIntent);
	}

	public static void showNotification(Context context, String title,
			String body, int notifyId, Intent startIntent) {

		// 这里是弹出notifacation的代码

		NotificationManager notificationManager = (NotificationManager) context
				.getSystemService(context.NOTIFICATION_SERVICE);

		Notification notification = new Notification(R.drawable.ic_launcher,
				"", System.currentTimeMillis());

		notification.defaults = Notification.DEFAULT_SOUND;// 声音
		notification.defaults = Notification.DEFAULT_VIBRATE;// 震动

		notification.flags = Notification.FLAG_AUTO_CANCEL;

		PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
				startIntent, 0);

		notification.setLatestEventInfo(context, title, body, contentIntent);

		notificationManager.notify(notifyId, notification);

	}
}
